<script setup>
import { nextTick, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { Message } from "@arco-design/web-vue";
import roleApi from "@/api/roleApi";
import userApi from "@/api/userApi";
import constants from "@/utils/constants";
import tool from "@/utils/tool";

const router = useRouter();

const submitForm = ref();
const searchForm = ref();
const searchModel = reactive({
  createUserId: "",
});
const visible = ref(false);
let uploadVisible = ref(false);
const loading = ref(false);

let submitData = ref({
  opened: false,
  checkedKeys: [],
  halfCheckedKeys: []
});
const menus = ref([]);
let checkedKeys = ref([]);

let pagination = reactive({
  total: 0,
  current: 1,
  pageSize: 15,
  showPageSize: true,
  pageSizeOptions: [15, 25, 30, 50],
  showTotal: true,
  pageChange: (current) => {
    pagination.current = current;
    search(current, pagination.pageSize);
  },
  pageSizeChange(size) {
    pagination.pageSize = size;
    search(pagination.current, size);
  },
});

const columns = [
  {
    title: "角色名称",
    dataIndex: "name",
    width: 100,
  },
  {
    title: "角色编码",
    dataIndex: "code",
    width: 100,
  },
  {
    title: "是否公开",
    slotName: "opened",
    width: 100,
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    width: 180,
  },
  {
    title: "操作",
    slotName: "action",
    fixed: "right",
    width: 200,
  },
];
const data = ref([]);

const showAddDialog = () => {
  visible.value = true;
  nextTick(() => {
    submitForm.value.resetFields();
    submitData.value = {
      opened: false,
      checkedKeys: [],
      halfCheckedKeys: []
    };
  })
};

const editRecord = (record) => {
  visible.value = true;
  nextTick(() => {
    submitForm.value.resetFields();
    submitData.value = Object.assign({}, record);
  });
};

const deleteRecord = (record) => {
  roleApi
    .delete({
      id: record.id,
    })
    .then((res) => {
      search(1, 15);
    });
};

const handleSubmitSuccess = (values, e) => {
  if (!values.halfCheckedKeys) {
    values.halfCheckedKeys = []
  }
  const mergedKeys = [...new Set([...values.checkedKeys, ...values.halfCheckedKeys])];
  values.selectKeys = mergedKeys;
  roleApi.save(values).then((res) => {
    visible.value = false;
    Message.success("保存成功");
    search(1, 15);
  });
};

const search = (current = 1, size = 15) => {
  var params = {
    pageNo: current,
    pageSize: size,
    queryParam: Object.assign({}, searchModel),
  };
  loading.value = true;
  roleApi.queryPage(params).then((res) => {
    data.value = res.records;
    pagination.total = res.total;
    loading.value = false;
  });
};

const refresh = () => {
  search(1, 15);
};

const reset = () => {
  searchForm.value.resetFields();
};

const queryMenuTree = () => {
  let userId = tool.data.get("loginId");
  userApi.queryMenuTree({ userId: userId }).then(res => {
    menus.value = res;
  })
}

search();
queryMenuTree();
</script>

<template>
  <div class="main-con">
    <a-card>
      <a-form ref="searchForm" :model="searchModel" :label-col-props="{ span: 8 }" :wrapper-col-props="{ span: 16 }"
        label-align="left">
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item field="name" label="角色名称">
              <a-input v-model="searchModel.name" placeholder="请输入角色名称" />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-space :size="18">
              <a-button type="primary" @click="refresh">
                <template #icon>
                  <icon-search />
                </template>
                查询
              </a-button>
              <a-button @click="reset">
                <template #icon>
                  <icon-refresh />
                </template>
                重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>
    </a-card>
    <a-card style="margin-top: 20px">
      <div class="toolbar">
        <a-space>
          <a-button type="primary" @click="showAddDialog">
            <template #icon>
              <icon-plus />
            </template>
            新增角色
          </a-button>
        </a-space>
      </div>
      <a-table :columns="columns" row-key="id" :loading="loading" :data="data" @page-change="pagination.pageChange"
        @page-size-change="pagination.pageSizeChange" :pagination="pagination" :bordered="false">

        <template #opened="{ record }">
          <a-tag>{{ record.opened ? '公开' : '私有' }}</a-tag>
        </template>
        <template #roleType="{ record }">
          {{
            constants.roleTypes.find((item) => {
              return item.value == record.roleType;
            }).label
          }}
        </template>
        <template #action="{ record }">
          <a-space>
            <a-button type="text" @click="editRecord(record)">编辑</a-button>
            <a-popconfirm content="确认要删除该数据吗？" @ok="deleteRecord(record)">
              <a-button type="text">删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>
    <a-modal v-model:visible="visible" title="新增角色" width="700px" :footer="null">
      <a-form ref="submitForm" size="large" :label-col-props="{ span: 6 }" :wrapper-col-props="{ span: 18 }"
        :model="submitData" @submit-success="handleSubmitSuccess">
        <a-form-item field="code" label="角色编码" :rules="[{ required: true, message: '请选择角色编码' }]">
          <a-input :disabled="submitData.id" v-model="submitData.code" placeholder="请输入角色编码"></a-input>
        </a-form-item>
        <a-form-item field="name" label="角色名称" :rules="[{ required: true, message: '请选择角色名称' }]">
          <a-input v-model="submitData.name" placeholder="请输入角色名称"></a-input>
        </a-form-item>
        <a-form-item field="opened" label="是否公开" :rules="[{ required: true, message: '请选择是否公开' }]">
          <a-switch v-model="submitData.opened"></a-switch>
        </a-form-item>
        <a-form-item label="选择权限">
          <a-spin style="width: 100%;">
            <a-card style="height: 400px;overflow-y: auto;">
              <a-tree :checkable="true" :field-names="{ title: 'name', key: 'id' }"
                v-model:checked-keys="submitData.checkedKeys" v-model:half-checked-keys="submitData.halfCheckedKeys"
                :only-check-leaf="true" :check-strictly="false" :data="menus">
                <template #extra="nodeData">
                  <a-tag color="cyan" v-if="nodeData.type == 3" size="mini">按钮</a-tag>
                </template>
              </a-tree>
            </a-card>
          </a-spin>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button html-type="submit" type="primary">保存</a-button>
            <a-button @click="() => {
              visible = false;
            }
              ">取消</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<style scoped></style>
